package ru.ifmo.network.skype.audio.receive;

import java.util.NavigableMap;
import java.util.TreeMap;

/**
 * @author avhaliullin
 */
public class AudioDataReceiver {
    private final int maxQueueSize;
    private final NavigableMap<Long, byte[]> queue = new TreeMap<Long, byte[]>();
    private long lastLabel = 0;

    public AudioDataReceiver(int maxQueueSize) {
        this.maxQueueSize = maxQueueSize;
        lastLabel = -maxQueueSize / 2;
    }

    public synchronized void message(long timeLabel, byte[] message) {
        queue.put(timeLabel, message);
        if (queue.size() > maxQueueSize) {
            System.out.println("Too long queue...");
            for (int i = 0; i < maxQueueSize / 2; i++) {
                queue.remove(queue.firstKey());
            }
            lastLabel = queue.firstKey() - 1;
        }
    }

    public synchronized byte[] getBuffer() {
        if (queue.isEmpty()) {
            lastLabel = -maxQueueSize / 2;
//            System.out.println("No data!");
            return null;
        }

        if (lastLabel < 0) {
            System.out.println("Skipping...");
            if (lastLabel <= -2) {
                lastLabel++;
                return null;
            }
            lastLabel = queue.firstKey() - 1;
            return null;
        }

        byte[] res = queue.get(lastLabel + 1);
        queue.remove(lastLabel + 1);
        if (res != null) {
            lastLabel++;
            return res;
        }

//        System.out.println("Skipping2...");
//        lastLabel = -maxQueueSize / 2;
        lastLabel++;
        return null;
    }
}
